import { createBrowserRouter, Navigate } from 'react-router-dom'
import routes from '@/router'
import { useState, useCallback, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { setDictionary, setMenu } from '@/store/dataSlice'
import { findDictionary } from '@/api/common'
import { findAllMenu } from '@/api/menu'
import { getFirstValidMenuAddress, getMenuTree } from '@/utils/menuUtils'

const useAppData = () => {
  const [router, setRouter] = useState({})
  const [loading, setLoading] = useState(false)
  const dispatch = useDispatch()
  const token = useSelector((state) => state.user.token)
  const menu = useSelector(state => state.data.menu)

  // 获取数据字典
  const getDictionary = useCallback(async () => {
    const { data } = await findDictionary()
    dispatch(setDictionary(data))
  }, [dispatch])

  // 获取菜单列表
  const getMenuList = useCallback(async () => {
    const { data } = await findAllMenu()
    dispatch(setMenu(data))
  }, [dispatch])

  const initData = useCallback(async () => {
    setLoading(false)
    await getDictionary()
    await getMenuList()
    setLoading(true)
  }, [getDictionary, getMenuList])

  useEffect(() => {
    // 初始化数据
    if (!token) {
      setRouter(createBrowserRouter(routes))
      setLoading(true)
      return
    }
    initData()
  }, [token, initData])

  useEffect(() => {
    if (menu.length > 0) {
      const menuTree = getMenuTree(menu)
      const firstValidMenuAddress = getFirstValidMenuAddress(menuTree)
      if (!firstValidMenuAddress) {
        return
      }
      menuTree.unshift({
        path : '/',
        element: <Navigate to={firstValidMenuAddress} />
      })

      routes[0].children = menuTree
      setRouter(createBrowserRouter(routes))
    }
  }, [menu])

  return { router, loading }
}

export default useAppData